<template>
<div class="my-chat">
    <x-header @on-click-back="$router.go(-1)" :left-options="{preventGoBack:true}">{{receiverInfo.nickname}}</x-header>
    <div class="my-chat">
        <section class="chatlist" :class="showSelBox>0?'chatlist-bottom-collapse':'chatlist-bottom'">
            <mt-loadmore :top-method="loadTop" top-pull-text="加载更多" top-drop-text="释放加载" @top-status-change="handleTopChange" ref="loadmore">
                <ul>
                    <div v-for="(item,i) in records" :key="i">
                      <li class="chat-mine" v-if="item.type==1">
                          <div class="chat-user"><avatar username="Lairenna" :src="item.avatar" :size="40"></avatar></div>
                          <div class="time"><cite><i>{{item.time}}</i>{{item.name}}</cite></div>
                          <div class="chat-text" v-html="replaceFace(item.content)"></div>
                      </li>
                      <li v-if="item.type==2">
                          <div class="chat-user"><avatar username="Lairenna" :src="item.avatar" :size="40"></avatar></div>
                          <div class="time"><cite>{{item.name}}<i>{{item.time}}</i></cite></div>
                          <div class="chat-text" v-html="replaceFace(item.content)"></div>
                      </li>
                    </div>
                </ul>
            </mt-loadmore>
        </section>
        <section class="foot">
            <mt-field id="txtContent" placeholder="请输入消息" class="con" v-model="content" @keyup.enter.native="sendMsg"></mt-field>
            <!-- <span class="btn-face" v-on:click="showSelBox=1"><i class="icon-fasmileo"></i></span> -->
            <span class="btn-face" v-on:click="showSelBox=showSelBox==1?0:1"><i class="icon-fasmileo" aria-hidden="true"></i></span>
            <!-- <span class="btn-plus" v-on:click="showSelBox=showSelBox==2?0:2"><i class="fa" aria-hidden="true" :class="showSelBox==2?'fa-minus-circle':'fa-plus-circle'"></i></span> -->
            <span class="btn" v-on:click="sendMsg"><i class="icon-fasong1"></i></span>
            <section class="selbox" :class="showSelBox>0?'show':'hide'">
                <section v-show="showSelBox==1" class="face-box">
                    <mt-swipe :auto="0" :continuous="false">
                        <mt-swipe-item :key="n" v-for="n in Math.ceil(EXPS.length/18)">
                          <li :key="index" v-for="(item, index) in getEXP(n,18)">
                              <img :src="'../../../static/emotion/'+item.file" alt="" :data="item.code" v-on:click="content+=item.code">
                          </li>
                        </mt-swipe-item>
                    </mt-swipe>
                </section>
                <!-- <div v-show="showSelBox==2">{{selOther}}</div> -->
            </section>
        </section>
    </div>
    </div>
</template>
<script>
import { Vue, Component } from 'vue-property-decorator';
import util from '../../js/chat.js';
import { XHeader } from 'vux';
import { namespace } from 'vuex-class';
import Avatar from 'vue-avatar';
const MineStore = namespace('mine');
@Component({
  components: { XHeader, Avatar }
})
export default class ChatList extends Vue {
  @MineStore.Action getServiceUser
  @MineStore.Action getMessages
  @MineStore.Action getSendMessage
  @MineStore.State sendMessage
  @MineStore.State messages
  @MineStore.State serviceUser
  userInfo = (localStorage.getItem('loginInfo') && JSON.parse(localStorage.getItem('loginInfo')).user) || ''
  showSelBox = 0 // 0隐藏 1显示表情 2显示其他
  selFace = '表情'
  // selOther = '其他功能'
  content = ''
  topStatus = ''
  records = []
  receiverInfo = {
    avatar: '',
    nickname: '',
    _id: ''
  }
  timer = null
  // 表情
  EXPS = [
    { file: '100.gif', code: '/::)', title: '微笑', reg: /\/::\)/g },
    { file: '101.gif', code: '/::~', title: '伤心', reg: /\/::~/g },
    { file: '102.gif', code: '/::B', title: '美女', reg: /\/::B/g },
    { file: '103.gif', code: '/::|', title: '发呆', reg: /\/::\|/g },
    { file: '104.gif', code: '/:8-)', title: '墨镜', reg: /\/:8-\)/g },
    { file: '105.gif', code: '/::<', title: '哭', reg: /\/::</g },
    { file: '106.gif', code: '/::$', title: '羞', reg: /\/::\$/g },
    { file: '107.gif', code: '/::X', title: '哑', reg: /\/::X/g },
    { file: '108.gif', code: '/::Z', title: '睡', reg: /\/::Z/g },
    { file: '109.gif', code: '/::\'(', title: '哭', reg: /\/::'\(/g },
    { file: '110.gif', code: '/::-|', title: '囧', reg: /\/::-\|/g },
    { file: '111.gif', code: '/::@', title: '怒', reg: /\/::@/g },
    { file: '112.gif', code: '/::P', title: '调皮', reg: /\/::P/g },
    { file: '113.gif', code: '/::D', title: '笑', reg: /\/::D/g },
    { file: '114.gif', code: '/::O', title: '惊讶', reg: /\/::O/g },
    { file: '115.gif', code: '/::(', title: '难过', reg: /\/::\(/g },
    { file: '116.gif', code: '/::+', title: '酷', reg: /\/::\+/g },
    { file: '117.gif', code: '/:--b', title: '汗', reg: /\/:--b/g },
    { file: '118.gif', code: '/::Q', title: '抓狂', reg: /\/::Q/g },
    { file: '119.gif', code: '/::T', title: '吐', reg: /\/::T/g },
    { file: '120.gif', code: '/:,@P', title: '笑', reg: /\/:,@P/g },
    { file: '121.gif', code: '/:,@-D', title: '快乐', reg: /\/:,@-D/g },
    { file: '122.gif', code: '/::d', title: '奇', reg: /\/::d/g },
    { file: '123.gif', code: '/:,@o', title: '傲', reg: /\/:,@o/g },
    { file: '124.gif', code: '/::g', title: '饿', reg: /\/::g/g },
    { file: '125.gif', code: '/:|-)', title: '累', reg: /\/:\|-\)/g },
    { file: '126.gif', code: '/::!', title: '吓', reg: /\/::!/g }
  ]
  destroyed () {
    window.clearInterval(this.timer);
    this.$destroy();
  }
  getTimeOldMessages () {
    this.timer = window.setInterval(() => {
      this.getOldMessages()
    }, 10000)
  }
  getOldMessages () {
    const params = {
      receiverId: this.receiverInfo._id
    }
    this.getMessages(params).then(msg => {
      if (msg) {
        this.$vux.toast.text(msg, 'middle');
      } else {
        let _id = this.userInfo._id
        let arr = this.messages.list.map(v => {
          let flag = _id === v.senderId
          return {
            type: flag ? 1 : 2,
            time: util.formatDate.format(new Date(v.createTime * 1000), 'yyyy-MM-dd hh:mm:ss'),
            name: v.type === 1 ? v.receiver.nickname : v.sender.nickname,
            content: v.msg,
            id: v._id,
            avatar: v.type === 1 ? v.receiver.avatar : v.sender.avatar
          }
        })
        this.records = arr.reverse()
      }
    })
  }
  isService () {
    this.getServiceUser({}).then(msg => {
      if (msg) {
        this.$vux.toast.text(msg, 'middle');
      } else {
        this.receiverInfo = this.serviceUser
      }
    })
  }
  getEXP (pageNow, pageSize) {
    return this.EXPS.slice((pageNow - 1) * pageSize, pageSize * pageNow);
  }
  sendMsg () {
    if (this.content === '') {
      this.$vux.toast.text('请输入消息', 'middle')
      return;
    }
    const { nickname, _id, avatar } = this.userInfo
    this.records.push({
      type: 1,
      time: util.formatDate.format(new Date(), 'yyyy-MM-dd hh:mm:ss'),
      id: _id,
      content: this.content,
      avatar: avatar,
      name: nickname
    });
    const params = {
      msg: this.content,
      receiver: {
        avatar: this.receiverInfo.avatar,
        nickname: this.receiverInfo.nickname,
        _id: this.receiverInfo._id
      }
    }
    this.getSendMessage(params).then(msg => {
      if (msg) {
        this.$vux.toast.text(msg, 'middle');
      }
    })
    this.content = '';
    this.scrollToBottom();
  }
  // 聚焦输入框
  focusTxtContent () {
    document.querySelector('#txtContent input').focus();
  }
  // 滚动条滚动到底部
  scrollToBottom () {
    setTimeout(() => {
      let chatlist = document.getElementsByClassName('chatlist')[0];
      chatlist.scrollTop = chatlist.scrollHeight;
    }, 100);
  }
  // 替换表情代码
  replaceFace (con) {
    var exps = this.EXPS;
    for (var i = 0; i < exps.length; i++) {
      // con = con.replace(new RegExp(exps[i].code,'g'), '<img src='static/emotion/' + exps[i].file +''  alt='' />');
      con = con.replace(
        exps[i].reg,
        `<img src="../../../static/emotion/${exps[i].file}" alt=""/>`
      );
    }
    return con;
  }
  handleTopChange (status) {
    this.topStatus = status;
  }
  loadTop (id) {
    setTimeout(() => {
      let chatlist = document.getElementsByClassName('chatlist')[0];
      let oldHeight = chatlist.scrollHeight;
      this.getOldMessages()
      setTimeout(() => {
        let newHeight = chatlist.scrollHeight;
        chatlist.scrollTop = newHeight - oldHeight;
      }, 100);
      this.$refs.loadmore.onTopLoaded(id);
    }, 1500);
  }
  mounted () {
    if (this.$route.params.id === '0') {
      this.isService()
    } else {
      this.receiverInfo = JSON.parse(localStorage.getItem('receiverInfo'))
    }
    this.getTimeOldMessages()
    this.scrollToBottom();
    this.focusTxtContent();
    let timer = setTimeout(() => {
      this.getOldMessages()
      window.clearInterval(timer);
    }, 500)
  }
}
</script>
<style lang="less">
  .my-chat {
    .chatlist {
  position: absolute;
  top: 60px;
  bottom: 48px;
  left: 0px;
  right: 0px;
  overflow-y: scroll;
  overflow-x: hidden;
  padding: 10px;
}
.chatlist-bottom {
  bottom: 48px;
}

.chatlist-bottom-collapse {
  bottom: 198px;
}
ul{
      padding: 0;
  }
 li{
      list-style-type: none;
}
.chatlist ul {
  min-height: 300px;
}

.chatlist ul .chat-mine {
  text-align: right;
  padding-left: 0;
  padding-right: 60px;
}

.chatlist ul li {
  position: relative;
  /*font-size: 0;*/
  margin-bottom: 10px;
  padding-left: 60px;
  min-height: 68px;
}

.chat-mine .chat-user {
  left: auto;
  right: 3px;
}

.chat-user {
  position: absolute;
  left: 3px;
}

.chat-text,
.chat-user {
  display: inline-block;
  vertical-align: top;
}

.time {
  width: 100%;
}

cite {
  left: auto;
  right: 60px;
  text-align: right;
}

cite {
  font-style: normal;
  line-height: 24px;
  font-size: 12px;
  white-space: nowrap;
  color: #999;
  text-align: left;
}

cite i {
  font-style: normal;
  padding-left: 5px;
  padding-right: 5px;
  font-size: 12px;
}

.chat-mine .chat-text {
  margin-left: 0;
  text-align: left;
  background-color: #33df83;
  color: #fff;
}

.chat-text {
  position: relative;
  line-height: 22px;
  padding: 10px 15px;
  background-color: #eee;
  border-radius: 3px;
  color: #333;
  word-break: break-all;
  max-width: 462px\9;
}

.chat-text,
.chat-user {
  display: inline-block;
  vertical-align: top;
  font-size: 14px;
}

.chat-text img {
  max-width: 100%;
  vertical-align: middle;
}

.chat-user {
  position: absolute;
  left: 3px;
}

.chat-text:after {
  content: '';
  position: absolute;
  left: -10px;
  top: 15px;
  width: 0;
  height: 0;
  border-style: solid dashed dashed;
  border-color: #eee transparent transparent;
  overflow: hidden;
  border-width: 10px;
}

.chat-mine .chat-text:after {
  left: auto;
  right: -10px;
  border-top-color: #33df83;
}

.foot {
  width: 100%;
  min-height: 48px;
  position: fixed;
  bottom: 0px;
  left: 0px;
  background-color: #f8f8f8;
}

.foot .con {
  position: absolute;
  left: 10%;
  width: 75%;
}

.foot .btn-plus {
  width: 28px;
  padding: 9px 3px;
  position: absolute;
  left: 0px;
  border-left: 1px solid #d9d9d9;
}

.foot .btn-plus i {
  font-size: 2em;
  color: #ccc;
}

.foot .btn-face {
  float: left;
  width: 10%;
  height: 100%;
  line-height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
}

.foot .btn-face i {
  font-size: 30px;
  color: #d9d9d9;
}

.foot .selbox {
  height: 150px;
  margin-top: 48px;
}

.show {
  display: block;
}

.hide {
  display: none;
}

.face-box {
  padding: 15px 15px 0px 15px;
  overflow: hidden;
  width: 290px;
  margin: 0px auto;
  height: 135px;
}

.face-box li {
  width: 30px;
  float: left;
  padding: 6px 10px 0px 8px;
}

.btn {
  display: inline-block;
  vertical-align: top;
  width: 15%;
  text-align: center;
  background-color: #ffffff;
  i {
    color: #d9d9d9;
    font-size: 30px;
  }
  color: #fff;
  position: absolute;
  right: 0px;
}
.mint-cell-wrapper {
  background-image: none;
}
.mint-swipe-indicator {
  background: #333333;
}
.mint-swipe-indicator.is-active {
  background: #000000;
}
  }
</style>
